package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    /**
     * 系统启动时初始化店铺类型缓存
     */
    @PostConstruct
    public void init() {
        try {
            log.info("初始化店铺类型缓存");
            cacheShopType();
            log.info("店铺类型缓存初始化完成");
        } catch (Exception e) {
            log.error("店铺类型缓存初始化失败", e);
        }
    }
    
    /**
     * 将店铺类型数据缓存到Redis
     */
    public void cacheShopType() {
        // 1. 查询所有店铺类型数据
        List<ShopType> typeList = query().orderByAsc("sort").list();
        
        // 2. 判断数据是否存在
        if (typeList == null || typeList.isEmpty()) {
            return;
        }
        
        // 3. 存在，写入Redis
        String jsonStr = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, jsonStr, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
    }
}
